<template>
	<div class="competition-page">
		<header>
			<h1>竞赛题目</h1>
			<button onclick="location.href='/mypage'">我的主页</button>
		</header>

		<div class="main-content">
			<div class="left-panel">
				<!-- 搜索框 -->
				<div class="search-bar">
					<input v-model="searchQuery" type="text" placeholder="搜索题目...">
					<button @click="searchProblems">搜索</button>
				</div>

				<!-- 分类按钮 -->
				<div class="category-buttons">
					<button v-for="category in categories" :key="category.value" @click="setCategory(category.value)"
						:class="{ active: currentCategory === category.value }">
						{{ category.label }}
					</button>
				</div>

				<!-- 题目列表 -->
				<div v-if="loading" class="loading">加载中...</div>
				<div v-else>
					<div v-if="paginatedProblems.length === 0" class="no-results">
						没有找到匹配的题目
					</div>
					<div v-else class="problem-list">
						<div v-for="problem in paginatedProblems" :key="problem.id" class="problem-item"
							@click="goToProblemDetail(problem.id)">
							<span class="problem-number">{{ problem.id }}.</span>
							{{ problem.title }}
							<span v-if="problem.completed" class="completed-tag">已完成</span>
						</div>
					</div>
				</div>

				<!-- 分页控件 -->
				<div class="pagination">
					<button @click="changePage(-1)" :disabled="currentPage === 1">
						上一页
					</button>
					<span>{{ currentPage }} / {{ totalPages }}</span>
					<button @click="changePage(1)" :disabled="currentPage === totalPages">
						下一页
					</button>
				</div>
			</div>

			<div class="right-panel">
				<!-- 用户信息 -->
				<div v-if="userLoading" class="loading">加载用户信息...</div>
				<div v-else-if="userError" class="error">{{ userError }}</div>
				<div v-else class="user-info">
					<h3>用户信息</h3>
					<p>用户名：{{ username }}</p>
					<p>解题数：{{ solvedProblems }}</p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import axios from 'axios';
import { config } from '../utils/constant.js'
export default {
	name: 'CompetitionPage',
	data() {
		return {
			problems: [],
			categories: [
				{ value: 'all', label: '全部' },
				{ value: 'niuke', label: '牛客竞赛' },
				{ value: 'luogu', label: '洛谷' },
				{ value: 'cf', label: 'Codeforces' }
			],
			currentCategory: 'all',
			searchQuery: '',
			username: '默认用户',
			solvedProblems: 0,
			loading: false,
			userLoading: false,
			userError: null,
			currentPage: 1,
			pageSize: 15
		}
	},
	computed: {
		filteredProblems() {
			return this.problems.filter(problem => {
				const categoryMatch = this.currentCategory === 'all' || problem.category === this.currentCategory;
				const searchMatch = problem.title.toLowerCase().includes(this.searchQuery.toLowerCase());
				return categoryMatch && searchMatch;
			});
		},
		totalPages() {
			return Math.ceil(this.filteredProblems.length / this.pageSize);
		},
		paginatedProblems() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.filteredProblems.slice(start, end);
		}
	},
	methods: {
		async fetchProblems() {
			this.loading = true;
			try {
				const response = await axios.get(config.baseUrl + '/problem/list/');
				if (response.data && response.data.banks) {
					this.problems = response.data.banks.map(item => ({
						id: item.problem_number, // 使用 problem_number 作为 id
						title: item.problem_name,
						category: 'niuke', // 假设所有问题都属于niuke类别，根据实际情况调整
						completed: false // 假设所有问题都未完成，根据实际情况调整
					}));
				}
			} catch (error) {
				console.error('Error fetching problems:', error);
			} finally {
				this.loading = false;
			}
		},
		setCategory(category) {
			this.currentCategory = category;
			this.currentPage = 1;
		},
		searchProblems() {
			this.currentPage = 1;
		},
		async fetchUserInfo() {
			this.userLoading = true;
			this.userError = null;
			try {
				const response = await axios.get('/api/user-info');
				this.username = response.data.username;
				this.solvedProblems = response.data.solvedProblems;
			} catch (error) {
				console.error('Error fetching user info:', error);
				this.userError = '获取用户信息失败，请稍后再试';
			} finally {
				this.userLoading = false;
			}
		},
		changePage(delta) {
			const newPage = this.currentPage + delta;
			if (newPage >= 1 && newPage <= this.totalPages) {
				this.currentPage = newPage;
			}
		},
		goToProblemDetail(problemId) {
			this.$router.push({ name: 'problem', params: { id: problemId } });
		},
		async fetchCompletedProblems() {
			try {
				const response = await axios.get('/api/completed-problems');
				const completedProblemIds = response.data;
				this.problems.forEach(problem => {
					problem.completed = completedProblemIds.includes(problem.id);
				});
				this.solvedProblems = completedProblemIds.length;
			} catch (error) {
				console.error('Error fetching completed problems:', error);
			}
		}
	},
	created() {
		this.fetchProblems();
		// this.fetchUserInfo();
		// this.fetchCompletedProblems();
	}
}
</script>

<style scoped>
.competition-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	font-family: Arial, sans-serif;
}

header {
	background-color: #62aad4;
	color: white;
	padding: 2rem;
	text-align: center;
	letter-spacing: 4px;
}

header button {
	position: absolute;
	right: 20px;
	top: 20px;
	width: 100px;
	height: 100px;
	border: none;
	background-color: wheat;
	/* 绿色背景，根据需要修改 */
	border-radius: 50%;
	/* 使按钮圆形 */
	/* background-image: url('https://tse1-mm.cn.bing.net/th/id/OIP-C._8izqMlxf9yICABnk14F7AHaHa?rs=1&pid=ImgDetMainfavicon');  */
	/* 设置头像图片，替换为你的头像图片路径 */
	background-size: cover;
	/* 覆盖整个按钮 */
	background-position: center;
	/* 图片居中显示 */
	font-size: 18px;
	/* 设置字体大小 */
	line-height: 40px;
	/* 设置行高，使文字垂直居中 */
	/* color: white; 设置字体颜色 */
	text-align: center;
	font-weight: bold;
}

/* 如果需要添加过渡效果，可以添加以下CSS */
header button:hover {
	background-color: white;
	/* 按钮被点击时的背景颜色 */
}

.main-content {
	display: flex;
	flex: 1;
	letter-spacing: 4px;
}

.left-panel {
	flex: 3;
	padding: 1rem;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
}

.right-panel {
	flex: 1;
	padding: 2rem;
	background-color: #f0f0f0;
}

.search-bar {
	border: 1px solid #7bc8f5;
	margin-bottom: 2rem;
	display: flex;
}

.search-bar input {
	border: 1px solid #7bc8f5;
	flex: 2;
	padding: 1rem;
	font-size: 1.2rem;
}

.search-bar button {
	padding: 0.5rem 1rem;
	background-color: #7bc8f5;
	color: white;
	border: none;
	cursor: pointer;
}

.category-buttons {
	margin-bottom: 1rem;
	display: flex;
	flex-wrap: wrap;
}

.category-buttons button {
	margin-right: 50px;
	margin-bottom: 10px;
	padding: 0.5rem 1rem;
	border: 1px solid #ddd;
	background-color: white;
	cursor: pointer;
	transition: background-color 0.3s;
}

.category-buttons button.active {
	background-color: #7bc8f5;
	color: white;
}

.problem-list {
	border-top: 2px solid #76eded;
	flex-grow: 1;
}

.problem-item {
	padding: 1rem;
	border-bottom: 1.5px solid #76eded;
	cursor: pointer;
	display: flex;
	align-items: center;
}

.problem-number {
	font-weight: bold;
	margin-right: 0.5rem;
}

.completed-tag {
	margin-left: auto;
	background-color: #4CAF50;
	color: white;
	padding: 0.2rem 0.5rem;
	border-radius: 4px;
	font-size: 0.8rem;
}

.user-info {
	background-color: white;
	padding: 1rem;
	border-radius: 4px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading,
.error,
.no-results {
	padding: 1rem;
	text-align: center;
}

.error {
	color: red;
}

.no-results {
	color: #666;
	font-style: italic;
}

.pagination {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 1rem;
}

.pagination button {
	padding: 0.5rem 1rem;
	margin: 0 0.5rem;
	background-color: #72beea;
	color: white;
	border: none;
	cursor: pointer;
}

.pagination button:disabled {
	background-color: #ccc;
	cursor: not-allowed;
}

.pagination span {
	margin: 0 0.5rem;
}
</style>